package weapon

import (
	"cloud_worm/wormweb/controllers/ctrconfig"
	"cloud_worm/wormweb/controllers/ctrutil"
	"fmt"
	"github.com/astaxie/beego/logs"
	"os"
	"path/filepath"
	"cloud_worm/wormweb/controllers/ctrinner/analyzer"
	"cloud_worm/util/umodels/mysqldb/dbtask"
	"cloud_worm/util/umodels/mysqldb"
	"cloud_worm/util/uhttp"
)

// AlertReportController alert告警详情的报告
type AlertReportController struct {
	ctrconfig.LoginCtr
}

// GetReportByTaskId 获取指定task id的alert报告
func (a *AlertReportController) GetReportByTaskId()  {
	if a.Guest() == false {
		return
	}

	// 解析参数
	taskId := a.GetString("task_id", mysqldb.SelectStrAll)
	if taskId == mysqldb.SelectStrAll {
		errMsg := fmt.Sprintf("input task id error")
		logs.Error(errMsg)
		a.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, errMsg, nil)
		a.ServeJSON()
		return
	}

	// 检查task id
	task := &dbtask.WeaponTask{TaskId: taskId}
	err := task.Read("task_id")
	if err != nil {
		errMsg := fmt.Sprintf("no input task id record: %s", err.Error())
		logs.Error(errMsg)
		a.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, errMsg, nil)
		a.ServeJSON()
		return
	}

	// 检查文件是否存在
	fileName := filepath.Join(ctrutil.ReportDataDir, ctrutil.AlertReportDir, fmt.Sprintf("%s.xlsx", taskId))
	_, err = os.Stat(fileName)
	if err != nil {
		// 尝试分析
		item := &analyzer.ComputeTaskAlerts{TaskId: taskId}
		analyzer.ComputeQueueInstance().MsgQ.Push(item)

		errMsg := fmt.Sprintf("task '%s' no report file: %s", taskId, err.Error())
		logs.Error(errMsg)
		a.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, errMsg, nil)
		a.ServeJSON()
		return
	}

	a.Ctx.Output.Download(fileName)
	return
}

